package com.manelrodriguez.applications.ibex35.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.manelrodriguez.applications.ibex35.R;
import com.manelrodriguez.applications.ibex35.adapters.CotizacionListAdapter;
import com.manelrodriguez.applications.ibex35.to.Empresa;
import com.manelrodriguez.applications.ibex35.utils.Constantes;
import com.manelrodriguez.applications.ibex35.utils.DescargaCotizacionesYahoo;
import com.manelrodriguez.applications.ibex35.utils.StocksURLS;


public class Ibex35Activity extends Activity implements OnItemClickListener{
	private ProgressDialog m_ProgressDialog = null;
	public static ArrayList<Empresa> m_empresas = null;
	public static Map<String,Empresa> hash_empresas = null;
	private CotizacionListAdapter m_adapter;
	PullToRefreshListView lv;
	Intent intent;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        m_empresas = new ArrayList<Empresa>();
        hash_empresas = new HashMap<String, Empresa>();
        this.m_adapter = new CotizacionListAdapter(this, R.layout.list_item, m_empresas);
        lv = (PullToRefreshListView)findViewById(R.id.listView1);
        lv.setAdapter(this.m_adapter);
        lv.setOnItemClickListener(this);
        registerForContextMenu(lv);
		
        lv.setOnRefreshListener(new OnRefreshListener<ListView>() {
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				
				try{
					new DescargarCotizaciones().execute(new URL(StocksURLS.URL_YAHOO));
	            } catch (MalformedURLException e) {
	            	//Toast.makeText(this, getString(R.string.errorURL), Toast.LENGTH_LONG).show();
	     		}
			}
		});

        
        try{
        	new DescargarCotizaciones().execute(new URL(StocksURLS.URL_YAHOO));
        } catch (MalformedURLException e) {
		}
    }
    
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
    	intent = new Intent(getApplicationContext(), DetalleCotizacionActivity.class);
    	intent.putExtra(Constantes.EMPRESA, m_empresas.get(position-1));
    	intent.putExtra(Constantes.POSICION, position-1);
		startActivity(intent);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	if (v.getId()==R.id.listView1) {
    		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    	    menu.setHeaderTitle(m_empresas.get(info.position-1).getCompanyName());
    	    menu.add(0, v.getId(), 0, getString(R.string.anadirFavorito));
    	}
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
	        case R.id.menu_actualizar:
	        	 try{
	        		 new DescargarCotizaciones().execute(new URL(StocksURLS.URL_YAHOO));
	             } catch (MalformedURLException e) {
	            	 Toast.makeText(this, getString(R.string.errorURL), Toast.LENGTH_LONG).show();
	     		 }
	            return true;
	        case R.id.menu_favoritos:
	        	intent = new Intent(getApplicationContext(), FavoritosActivity.class);
	    		startActivity(intent);
	            return true;
	        case R.id.menu_cartera:
	        	intent = new Intent(getApplicationContext(), CarteraActivity.class);
	    		startActivity(intent);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	if (item.getTitle().equals(getString(R.string.anadirFavorito))) {
    		Empresa empresa = m_empresas.get(info.position-1);
        	if(empresa.addFavorite(info.position-1, this)){
        		Toast.makeText(Ibex35Activity.this, getString(R.string.anadido), Toast.LENGTH_SHORT).show();
        	}
    	}

       return true;
    }
    
    public class DescargarCotizaciones extends AsyncTask<URL, Void, Integer>{
    	@Override
    	protected void onPreExecute() {
    		super.onPreExecute();
    		m_empresas.clear();
    		hash_empresas.clear();
    		m_ProgressDialog = ProgressDialog.show(Ibex35Activity.this,getString(R.string.porfavor), getString(R.string.obteniendoDatos), true);
    	}
    	
    	@Override
    	protected Integer doInBackground(URL... params) {
    		DescargaCotizacionesYahoo descarga = new DescargaCotizacionesYahoo();
    		int resultado = descarga.descargar(params[0], m_empresas, hash_empresas, getApplicationContext());
    		return resultado;
    	}
    	
    	@Override
    	protected void onPostExecute(Integer result) {
    		m_ProgressDialog.dismiss();
    		//super.onPostExecute(result);
    		switch(result){
    		case StocksURLS.ERROR_URL:Toast.makeText(Ibex35Activity.this, getString(R.string.errorURL), Toast.LENGTH_LONG).show();
    			break;
    		case StocksURLS.ERROR_CONECTION:Toast.makeText(Ibex35Activity.this, getString(R.string.errorConexion), Toast.LENGTH_LONG).show();
    			break;
    		case StocksURLS.ERROR_DATE:Toast.makeText(Ibex35Activity.this, getString(R.string.errorFechas), Toast.LENGTH_LONG).show();
    			break;
    		case StocksURLS.RESULT_OK:
    			if(m_empresas != null && m_empresas.size() > 0){
        			m_adapter.notifyDataSetChanged();
        		}
    			break;
    		}
    		lv.onRefreshComplete();
            super.onPostExecute(result);
    	}
    }
}